package com.sanjin.filter;

import com.sanjin.entity.Admin;
import com.sanjin.entity.WxMiniUser;
import com.sanjin.service.WxMiniUserService;
import com.sanjin.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/5/10 11:02
 */
@Component
public class JwtAuthenticationWxMiniUserFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private WxMiniUserService wxMiniUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestToken = request.getHeader(jwtUtils.getHeader());
        // 对于微信小程序用户 requestsUsername 是用户的 openid
        String requestUsername = jwtUtils.getUsernameFromToken(requestToken);
        WxMiniUser wxMiniUser = wxMiniUserService.queryWxMiniUserByOpenid(requestUsername);
        // token 没过期
        if (wxMiniUser != null && requestToken != null && jwtUtils.validateToken(requestToken, wxMiniUser.getUsername())) {
            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        wxMiniUser.getUsername(),
                        wxMiniUser.getPassword(),
                        wxMiniUser.getAuthorities()
                );
                // 设置 details 信息，包含 sessionId，请求IP等详细信息
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
